手写一个简单的SpringBoot Starter |
您所在的位置:网站首页 › maven snapshot › 手写一个简单的SpringBoot Starter |
现在各种自定义的starter屡见不鲜,也许就需要自己来自定义一个starter了。学习一下starter的构建必备 starter-定义首先需要自顶一个配置bean package com.zhao.starter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; @EnableConfigurationProperties(StarterBean.class) @ConfigurationProperties(prefix = "starterbean") public class StarterBean { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "StarterBean{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } }然后需要通过Springboot自动注入的注解,以及Spring spi 的spring.factories将配置bean加入自动配置的管理 @Configuration @ConditionalOnClass public class StartBeanAutoConfiguration { static { System.out.println("custom auto configuration init "); } @Bean public StarterBean starterBean(){ return new StarterBean(); } }资源目录下新建META-INF文件夹下spring.factories文件, org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.zhao.starter.StartBeanAutoConfigurationpom文件 4.0.0 com.zhao starter-demo 1.0-SNAPSHOT org.springframework.boot spring-boot-autoconfigure 2.2.2.RELEASE使用maven install之后就可以在新建项目时使用了。 starter使用测试pom定义 4.0.0 com.zhao starter-use-demo 1.0-SNAPSHOT com.zhao starter-demo 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web 2.2.2.RELEASE org.springframework.boot spring-boot-starter-test 2.2.2.RELEASE test启动类 @SpringBootApplication public class StarterUseApplication { public static void main(String[] args) { SpringApplication.run(StarterUseApplication.class,args); } }配置starter需要的bean的配置 starterbean.id=test123 starterbean.name=zhaozhen测试类 @RunWith(SpringRunner.class) @SpringBootTest(classes = StarterUseApplication.class) public class StarterUseTest { @Autowired StarterBean starterBean; @Test public void starUse(){ System.out.println(starterBean); } }测试结果,正常使用 file欢迎关注和点赞,以及总结的分类面试题https://github.com/zhendiao/JavaInterview |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |